package com.blb.socket.demo3;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.net.ServerSocket;
import java.net.Socket;

/**
 * 文件服务器
 */
public class FileServer {

    public static final int PORT = 8888;

    public static final String FILE_DIR = "D:\\upload\\";

    public void start(){
        System.out.println("启动文件服务器");
        //创建ServerSocket
        try(ServerSocket serverSocket = new ServerSocket(PORT)){
            while(true){
                //获得客户端
                Socket client = serverSocket.accept();
                try(ObjectInputStream is = new ObjectInputStream(client.getInputStream())){
                    //读取文件名
                    String filename = is.readUTF();
                    //目录不存在可以创建
                    File dir = new File(FILE_DIR);
                    if(!dir.exists()){
                        dir.mkdir();
                    }
                    //创建文件输出流
                    FileOutputStream fos = new FileOutputStream(FILE_DIR + filename);
                    byte[] buf = new byte[1024];
                    int len = 0;
                    //循环从输入流中读取字节，返回读取长度
                    while((len = is.read(buf)) != -1){
                        //写入磁盘文件中
                        fos.write(buf,0,len);
                    }
                    fos.flush();
                    fos.close();
                    System.out.println(filename+"写入成功！");
                }catch (IOException ex){
                    ex.printStackTrace();
                }
            }
        }catch (IOException ex){
            ex.printStackTrace();
        }
    }

    public static void main(String[] args) {
        new FileServer().start();
    }
}
